<?php

namespace app\shop\service;
use app\common\service\Result;
use app\shop\model\document\Contract as ContractModel;
use app\shop\model\document\ContractTpl;
use app\shop\model\user\User;
use Dompdf\Dompdf;
/**
 * 合同
 */
class Contract
{
    public function tplList($data)
    {
        $where = [
            ['app_id', '=', request()->app_id]
        ];
        if (!empty($data['keyword'])) {
            $where[] = ['title', 'like', '%' . $data['keyword'] . '%'];
        }
        $list = ContractTpl::where($where)->order('id desc')->paginate($data['page_size'] ?? 20);
        return Result::success($list);
    }
    public function addTpl($data)
    {
        try {
            $data['app_id'] = request()->app_id;
            $tpl = ContractTpl::create($data);
            return Result::success($tpl);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function editTpl($data)
    {
        try {
            $tpl = ContractTpl::find($data['id']);
            $tpl->save($data);
            return Result::success($tpl);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function deleteTpl($id)
    {
        try {
            $tpl = ContractTpl::find($id);
            $tpl->delete();
            return Result::success($tpl);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }
    public function tplForm($id)
    {
        try {
            $tpl = ContractTpl::field('id,title,content,field')->find($id);
            return Result::success($tpl);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function list($data)
    {
        try {
            $map = [
                ['app_id', '=', request()->app_id]
            ];
            $user_id = $data['user_id'] ?? 0;
            if ($user_id) {
                $map[] = ['user_id', '=', $user_id];
            }
            $status = $data['status'] ?? -1;
            if ($status != -1) {
                $map[] = ['status', '=', $status];
            }
            $list = ContractModel::where($map)->with('user')->order('status,id desc')->paginate($data['pageSize'] ?? 20);
            return Result::success($list);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function info($id)
    {
        try {
            $info = ContractModel::with('user')->find($id);
            return Result::success($info);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function add($data)
    {
        try {
            $tpl = ContractTpl::find($data['tpl_id']);
            if (!$tpl) {
                throw new \Exception('模板不存在');
            }
            $user = User::find($data['user_id']);
            if (!$user) {
                throw new \Exception('用户不存在');
            }
            $add_data = [
                'user_id' => $data['user_id'],
                'title' => $tpl['title'],
                'tpl_content' => $data['content'],
                'content' => $tpl['content'],
                'app_id' => request()->app_id,
            ];
            $field = [];
            foreach ($tpl['field'] as $v) {
                $field[$v] = "";
            }
            $add_data['field'] = $field;
            $info = ContractModel::create($add_data);
            return Result::success('添加成功');
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function edit($data)
    {
        try {
            $info = ContractModel::find($data['id']);
            if (!$info) {
                return Result::error('合同不存在');
            }
            if ($info['user_id'] != $data['user_id']) {
                return Result::error('无权操作');
            }
            if ($info->status == 1) {
                return Result::error('合同已生效，无法修改');
            }
            //更新 field,content 字段
            //把tpl_content的对应字段替换为用户填写内容
            $tpl_content = $info->tpl_content;
            unset($data['id']);
            unset($data['user_id']);
            $field = $data;
            $content = $tpl_content;
            foreach ($field as $key => $value) {
                $content = str_replace('{{' . $key . '}}', $value, $content);
            }
            $save_data = [
                'field' => $field,
                'content' => $content,
            ];
            $info->save($save_data);
            return Result::success($content);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function createPdf($id)
    {
        try {
            $info = ContractModel::with('user')->find($id);
            if (!$info) {
                return Result::error('合同不存在');
            }
            //生成offer文件pdf
            $dompdf = new Dompdf([
                'isRemoteEnabled' => true,
                'isPhpEnabled' => true,
                'defaultFont' => 'stsong', // 支持中文的字体
            ]);
            $templateContent = file_get_contents(app()->getRootPath() . 'public/tpl/pdf/contract.html');
            // 填充数据到模板
            $templateContent = str_replace('{{page_title}}', htmlspecialchars($info->title, ENT_QUOTES, 'UTF-8'), $templateContent);
            $templateContent = str_replace('{{content}}', $info->content, $templateContent);
            $dompdf->loadHtml($templateContent, 'UTF-8');
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            $file_path = app()->getRootPath() . 'public/download/contract/';

            if (!is_dir($file_path)) {
                mkdir($file_path, 0777, true);
            }
            $file_name = $info['title'] . '-' . $info['user']['real_name'] . '.pdf';
            $outputPath = $file_path . $file_name;
            file_put_contents($outputPath, $dompdf->output());
            // 返回成功结果
            $file_url = config('app.file_domain') . '/download/contract/' . $file_name;
            $info->file = $file_url;
            $info->save();
            return Result::success($file_url);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function sign($data)
    {
        try {
            $info = ContractModel::find($data['id']);
            if (!$info) {
                return Result::error('合同不存在');
            }
            if ($info->status == 1) {
                return Result::error('合同已签名');
            }
            if ($info->user_id != request()->user_id) {
                return Result::error('您无权操作');
            }
            $info->status = 1;
            $info->sign = $data['sign'];
            //$content = str_replace('{{签名}}', "<img src='".$data['sign']."' style='width:150px;'>", $info->content);
            //在content后面换行靠右加入签名和时间
            $content = $info->content . "<br><br><div style='text-align:right;'><img src='" . $data['sign'] . "' style='width:150px;'></div>";
            $content = $content . "<br><br><div style='text-align:right;'>" . date('Y-m-d H:i:s') . "</div>";
            $info->content = $content;
            $info->save();
            return Result::success('签名成功');
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }
}